package com.hht.wblib.utils;

import android.content.Context;
import android.content.Intent;

import java.lang.ref.WeakReference;

/**
 * Author:chen'hu
 * Time:2025/1/2 13:28
 * Description:这不是单例,防止内存泄漏
 */
public class IntentHelps {
    private Context mContext;
    private final Intent mIntent;
    private WeakReference<IntentConfigurator> mIntentConfiguratorWR;

    /**
     * @param mContext 上下文对象
     */
    private IntentHelps(Context mContext) {
        this.mContext = mContext.getApplicationContext();
        mIntent = new Intent();
        mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    }

    /**
     * @param context 上下文对象
     */
    public static IntentHelps getInstance(Context context) {
        return new IntentHelps(context);
    }


    public interface IntentConfigurator {
        void configure(Intent intent);
    }

    /**
     * @param configurator 配置文件接口
     */
    public IntentHelps setIntentConfigurator(IntentConfigurator configurator) {
        this.mIntentConfiguratorWR = new WeakReference<>(configurator);
        return this;
    }

    public boolean startActivity() {
        boolean isOpen = true;
        try {
            if (null != mIntentConfiguratorWR) {
                mIntentConfiguratorWR.get().configure(mIntent);
                mContext.startActivity(mIntent);
            } else {
                isOpen = false;
            }
        } catch (Exception e) {
            isOpen = false;
        } finally {
            return isOpen;
        }
    }


    /**
     * @return boolean
     */
    public boolean sendBroadCast() {
        boolean isOpen = true;
        try {
            if (null != mIntentConfiguratorWR) {
                mIntentConfiguratorWR.get().configure(mIntent);
                mContext.sendBroadcast(mIntent);
            } else {
                isOpen = false;
            }
        } catch (Exception e) {
            isOpen = false;
        } finally {
            return isOpen;
        }
    }

    public boolean startService() {
        boolean isOpen = true;
        try {
            if (null != mIntentConfiguratorWR) {
                mIntentConfiguratorWR.get().configure(mIntent);
                mContext.startService(mIntent);
            } else {
                isOpen = false;
            }
        } catch (Exception e) {
            isOpen = false;
        } finally {
            return isOpen;
        }
    }

}
